package com.zhkj.txg.module.home.ui

import android.view.View
import androidx.core.text.bold
import androidx.core.text.buildSpannedString
import androidx.core.text.scale
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.entity.node.BaseNode
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.txg.R
import com.zhkj.txg.module.cart.adapter.CartAdapter
import com.zhkj.txg.module.cart.adapter.OnCartItemSelectedListener
import com.zhkj.txg.module.cart.entity.CartProductEntity
import com.zhkj.txg.module.cart.vm.CartViewModel
import com.zhkj.txg.module.order.ui.OrderSubmitActivity
import com.zhkj.txg.module.product.ui.ProductDetailActivity
import kotlinx.android.synthetic.main.fragment_cart.*

class CartActivity : ViewModelActivity<CartViewModel>() {
    override fun setViewModel(): CartViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleCart
    override val layoutResId: Int = R.layout.fragment_cart

    /**
     * 0 - 结算模式,1 - 编辑模式
     */
    private var mode = 0
    private var refresh = false

    private val listener = object : OnCartItemSelectedListener {
        // 选中状态发生变化
        override fun changed() {
            refreshStatusAndPrice()
        }

        // 数量变化
        override fun numberChange(uiPosition: Int, type: Int, originNumber: Int, maxCount: Int) {
            setCartNumber(uiPosition, type, originNumber, maxCount)
            refreshStatusAndPrice()
        }

        // 删除购物车item
        override fun itemDelete(uiPosition: Int) {
            showConfirmPopupWindow(uiPosition)
        }

        override fun itemClick(uiPosition: Int, product: CartProductEntity) {
            if (mode == 0) {
                if (product.isGoodsOnSale()) ProductDetailActivity.normalProduct(
                    this@CartActivity,
                    product.goodsId,
                    true
                )
            } else {
                (cartAdapter.data[uiPosition] as? CartProductEntity)?.selected =
                    (cartAdapter.data[uiPosition] as? CartProductEntity)?.selected?.not() ?: false
                refreshStatusAndPrice(true)
            }
        }
    }

    // 购物车Adapter
    private val cartAdapter:CartAdapter by lazy {
        CartAdapter(listener)
    }

    override fun initUI() {
        with(titleCart) {
            showLeft(true).setLeftIcon(R.drawable.ic_arrow_left_black).setRightClickListener(View.OnClickListener {
                mode = if (mode == 0) 1 else 0
                refreshModeStatus()
            })
        }
        with(rvCartProduct) {
            layoutManager = LinearLayoutManager(this@CartActivity)
            adapter = cartAdapter
            (itemAnimator as? DefaultItemAnimator)?.supportsChangeAnimations = false
        }
        cartAdapter.setEmptyView(R.layout.layout_empty_data)
        // 全选按钮点击监听
        cbCartAll.setOnCheckedChangeListener { buttonView, isChecked ->
            if (buttonView.isPressed) {
                cartAdapter.refreshStatusEntity(true, isChecked,ignoreOnSale = mode == 1)
                refreshStatusAndPrice()
            }
        }
        // 结算按钮点击监听
        tvCartBuy.setOnClickListener {
            val cartIds = cartAdapter.getCartIds()
            OrderSubmitActivity.cartBuy(this, cartIds)
        }
        // 删除按钮点击监听
        tvCartDelete.setOnClickListener {
            val cartIds = cartAdapter.getCartIds()
            viewModel.deleteCart(AccountManager.getToken(), cartIds)
        }
        refreshCart.setOnRefreshListener {
            mode = 0
            refreshModeStatus()
            initData()
        }
    }

    @Suppress("UNCHECKED_CAST")
    override fun initViewModel() {
        // 购物车商品观察者
        viewModel.cartLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) {
                response.response?.data?.let {
                    // 数据填充
                    cartAdapter.setNewData(it.cartList as? MutableList<BaseNode>)
//                    tvCartTotal.text = SpanUtil.setPrefixMoneyStr("合计:", it.totalPrice)
                    tvCartTotal.text = buildSpannedString {
                        append("合计:￥").bold { scale(1.2F) { append(it.totalPrice) } }
                    }
                    refreshStatusAndPrice()
                    refreshCart.finishRefresh()
                }
            } else if (response.status == HttpResponseStatus.Status.FAILURE) refreshCart.finishRefresh(false)
        })
        // 购物车商品数量改变观察者
        viewModel.changeNumberLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.let {
                cartAdapter.refreshStatusEntity(cartId = it.cartId, number = it.currentNumber,ignoreOnSale = mode == 1)
                refreshStatusAndPrice()
            } else if (response.status == HttpResponseStatus.Status.FAILURE) cartAdapter.notifyDataSetChanged()
        })
        // 购物车商品删除观察者
        viewModel.deleteCartLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) {
                mode = 0
                refreshModeStatus()
                viewModel.getCart(AccountManager.getToken(), false)
            }
        })
        // 购物车商品刷新观察者
        viewModel.cartChangeSubscribe().observe(this, Observer { refresh = true })
        // 切换账户观察者
        viewModel.accountChangeSubscribe().observe(this, Observer { refresh = true })
    }

    override fun initData() {
        // 获取购物车参数
        viewModel.getCart(AccountManager.getToken(), false)
    }

    private fun refreshModeStatus() {
        titleCart.setRightTextContent(getString(if (mode == 0) R.string.edit else R.string.done))
        tvCartTotal.visibility = if (mode == 0) View.VISIBLE else View.INVISIBLE
        tvCartDelete.visibility = if (mode == 0) View.GONE else View.VISIBLE
        tvCartBuy.visibility = if (mode == 0) View.VISIBLE else View.GONE
    }

    /**
     * 刷新选中状态以及总价
     */
    private fun refreshStatusAndPrice(refresh: Boolean = false) {
        if (refresh) cartAdapter.notifyDataSetChanged()
        cartAdapter.refreshStatusEntity(ignoreOnSale = mode == 1)
        tvCartTotal.text = buildSpannedString {
            append("合计:￥").bold { scale(1.2F) { append(cartAdapter.checkStatusEntity.totalPrice) } }
        }
        cbCartAll.isChecked = cartAdapter.checkStatusEntity.allSelected
        tvCartBuy.isEnabled = cartAdapter.checkStatusEntity.selectAny
        tvCartDelete.isEnabled = cartAdapter.checkStatusEntity.selectAny
    }

    /**
     * 设置商品数量,并刷新价格
     */
    private fun setCartNumber(uiPosition: Int, type: Int, originNumber: Int, maxStock: Int) {
        (cartAdapter.data[uiPosition] as? CartProductEntity)?.let {
            if (originNumber > maxStock) {
                toast(getString(R.string.more_than_stock))
                return
            }
            if (originNumber <= 0) {
                toast(getString(R.string.product_number_change))
                return
            }
            when (type) {
                0 -> viewModel.changeCartNumber(
                    AccountManager.getToken(),
                    it.cartId,
                    originNumber - 1
                )
                1 -> viewModel.changeCartNumber(
                    AccountManager.getToken(),
                    it.cartId,
                    originNumber + 1
                )
                else -> viewModel.changeCartNumber(AccountManager.getToken(), it.cartId, originNumber)
            }
        }
    }

    private fun showConfirmPopupWindow(uiPosition: Int) {
        (cartAdapter.data[uiPosition] as? CartProductEntity)?.let {
            viewModel.deleteCart(AccountManager.getToken(), it.cartId.toString())
        }
    }
}